<script setup>
import { updatePassword } from "@/api/user";
import { reactive, ref, watch } from "vue";
import "@material/web/textfield/outlined-text-field.js";
import "@material/web/button/text-button";
import MaterialDialog from "../MaterialDialog.vue";

const props = defineProps(["open", "user"]);
const emit = defineEmits(["open", "close", "done", "error"]);

const changePasswordForm = ref(null);
const repeatPassword = ref(null);

const formData = reactive({
  oldPassword: "",
  newPassword: "",
  repeatPassword: ""
});

watch(() => props.open, open => {
  if (open) {
    changePasswordForm.value.reset();
  }
});

watch(formData, () => {
  checkValidity();
});

function checkValidity() {
  if (formData.newPassword != formData.repeatPassword) {
    repeatPassword.value.setCustomValidity("两次输入的密码不相同");
    return false;
  }
  repeatPassword.value.setCustomValidity(null);
  return true;
}

async function onSubmit() {
  if (!changePasswordForm.value.reportValidity()) {
    return;
  }
  emit("close");
  try {
    await updatePassword(formData.oldPassword, formData.newPassword);
    emit("done");
  } catch (ex) {
    emit("error", ex.toString());
  }
}

function onReset() {
  formData.oldPassword = "";
  formData.newPassword = "";
  formData.repeatPassword = "";
}
</script>

<template>
  <MaterialDialog :open="open" @close="$emit('close')">
    <template #headline>
      修改密码
    </template>

    <template #content>
      <form id="change-password-form" ref="changePasswordForm" @submit.prevent="onSubmit" @reset="onReset">
        <p>
          <md-outlined-text-field label="旧密码" supporting-text="若没有设置密码则留空" type="password"
            @keypress.enter.prevent="() => { $refs.changePasswordForm.requestSubmit() }" autocomplete="password"
            v-model="formData.oldPassword">
          </md-outlined-text-field>
        </p>
        <p>
          <md-outlined-text-field label="新密码" type="password" required
            @keypress.enter.prevent="() => { $refs.changePasswordForm.requestSubmit() }" autocomplete="new-password"
            v-model="formData.newPassword">
          </md-outlined-text-field>
        </p>
        <p>
          <md-outlined-text-field ref="repeatPassword" label="确认密码" type="password" required
            @keypress.enter.prevent="() => { $refs.changePasswordForm.requestSubmit() }" autocomplete="new-password"
            v-model="formData.repeatPassword">
          </md-outlined-text-field>
        </p>
      </form>
    </template>

    <template #actions>
      <md-text-button type="reset" form="add-user-form">重置</md-text-button>
      <div style="flex: 1"></div>
      <md-text-button @click="$emit('close')">取消</md-text-button>
      <md-text-button type="submit" @click="() => { $refs.changePasswordForm.requestSubmit() }">修改</md-text-button>
    </template>
  </MaterialDialog>
</template>

<style>
#change-password-form>p {
  margin-bottom: 16px;
}

#change-password-form>p:last-child {
  margin-bottom: 0;
}
</style>